// 视频文案提取API服务

class VideoExtractor {
  constructor() {
    this.authKey = 'web-frontend-api-key-2025';
    this.baseUrl = ''; // 使用相对路径，通过代理访问
  }

  // 获取视频文案（使用付费API）
  async extractVideoText(url) {
    const requestData = {
      url,
      extract_text: true,  // 提取文案
      include_comments: false
    };

    const response = await fetch('/api/media/extract/web', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Auth-Key': this.authKey
      },
      body: JSON.stringify(requestData)
    });

    const result = await response.json();

    if (result.code === 200) {
      // 同步返回结果
      return result.data;
    } else if (result.code === 202) {
      // 异步任务，开始轮询
      return await this.pollTask(result.task_id);
    } else {
      throw new Error(result.message || '获取信息失败');
    }
  }

  // 轮询任务状态
  async pollTask(taskId) {
    return new Promise((resolve, reject) => {
      let attempts = 0;
      const maxAttempts = 150; // 5分钟超时 (150 * 2秒 = 5分钟)

      const pollInterval = setInterval(async () => {
        attempts++;
        
        try {
          const response = await fetch(`/api/media/extract/web/status/${taskId}`, {
            headers: { 'X-Auth-Key': this.authKey }
          });

          const result = await response.json();

          if (result.code === 200 && result.status === 'completed') {
            clearInterval(pollInterval);
            resolve(result.data);
          } else if (result.status === 'failed') {
            clearInterval(pollInterval);
            reject(new Error('视频解析失败，请检查链接是否正确'));
          } else if (attempts >= maxAttempts) {
            clearInterval(pollInterval);
            reject(new Error('处理超时，请稍后重试'));
          }
          // 继续轮询 (pending/processing状态)
        } catch (error) {
          console.error('轮询失败:', error);
          if (attempts >= maxAttempts) {
            clearInterval(pollInterval);
            reject(new Error('网络错误，请稍后重试'));
          }
        }
      }, 2000); // 每2秒轮询一次
    });
  }

  // 获取基础信息（免费API，需要加密）
  async getBasicInfo(url) {
    try {
      // 1. 获取ticket
      const ticketResponse = await fetch('/api/tkt/get_ticket');
      if (!ticketResponse.ok) {
        throw new Error('获取访问令牌失败');
      }
      
      const ticketData = await ticketResponse.json();
      const ticket = ticketData.ticket;

      if (!ticket) {
        throw new Error('无效的访问令牌');
      }

      // 2. 构造并加密请求数据
      const requestData = { url, extract_text: false };
      const encryptedData = this.encryptData(JSON.stringify(requestData), ticket);

      // 3. 发送请求
      const response = await fetch('/api/media/e1/bsc', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Ticket': ticket
        },
        body: JSON.stringify(encryptedData)
      });

      const result = await response.json();
      
      if (result.code === 200) {
        return result.data;
      } else {
        throw new Error(result.message || '获取基础信息失败');
      }
    } catch (error) {
      console.error('获取基础信息失败:', error);
      throw error;
    }
  }

  // 数据加密（需要crypto-js库）
  encryptData(data, ticket) {
    // 检查是否有crypto-js库
    if (typeof CryptoJS === 'undefined') {
      throw new Error('加密库未加载，请确保引入crypto-js');
    }

    const key = CryptoJS.SHA256(ticket);
    const iv = CryptoJS.lib.WordArray.random(16);

    const encrypted = CryptoJS.AES.encrypt(data, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });

    return {
      data: encrypted.toString(),
      iv: CryptoJS.enc.Base64.stringify(iv)
    };
  }
}

// 创建单例实例
const videoExtractor = new VideoExtractor();

// 导出方法
export const extractVideoText = (url) => videoExtractor.extractVideoText(url);
export const getBasicVideoInfo = (url) => videoExtractor.getBasicInfo(url);

export default videoExtractor;